package com.imageim.yimirror.ui.fragment;

import android.view.View;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.FashionBrandBean;
import com.imageim.yimirror.bean.FashionRecommendBean;
import com.imageim.yimirror.bean.LikeEventInfo;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.net.NetPresenterImpl;
import com.imageim.yimirror.net.NetView;
import com.imageim.yimirror.ui.adapter.FashionTrendBrandAdapter;
import com.imageim.yimirror.ui.fragment.base.BaseRecyclerViewFragment;
import com.imageim.yimirror.ui.widght.EmptyView;
import com.imageim.yimirror.ui.widght.LoadingView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.byteam.superadapter.SuperAdapter;
import org.byteam.superadapter.animation.ScaleInAnimation;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Yuaihen.
 * on 2018/12/27
 * 时尚趋势品牌Fragment
 */
public class FashionTrendFragment extends BaseRecyclerViewFragment implements NetView {

    @BindView(R.id.empty_view)
    EmptyView mEmptyView;
    @BindView(R.id.loading_view)
    LoadingView mLoadingView;
    private NetPresenterImpl mNetPresenter;
    private HashMap<String, String> map;
    private int currentPage = 1;
    private int mPageCount;
    private FashionTrendBrandAdapter mBrandAdapter;
    private List<FashionRecommendBean.ListBean> mRecommendDataList;
    private DressGuideFragment mDressGuideFragment;

    @Override
    protected void initListener() {
        super.initListener();
        mEmptyView.setOnFinishBtnClickListener(new EmptyView.OnFinishBtnClickListener() {
            @Override
            public void onFinishBtnClick() {
                getPersonalReport(MSG_REFRESH);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        mNetPresenter = new NetPresenterImpl(this);
        getPersonalReport(MSG_LOAD_DATA);
    }

    private static final int MSG_LOAD_DATA = 0x001;
    private static final int MSG_REFRESH = 0x002;
    private static final int MSG_LOAD_MORE = 0x003;


    /**
     * 获取用户形象报告
     *
     * @param loadType 加载类型  刷新/加载更多/首次加载
     */
    private void getPersonalReport(int loadType) {
        if (map == null) {
            map = new HashMap<>(4);
        }

        map.put(Constants.PHOTO_NO, UserUtil.getPhotoNo());
        map.put(Constants.CURRENT_PAGE, currentPage + "");
        //temp
        //        map.put("photoNo", "CN20181204193048Dy43");
        //        map.put("mac", "AC83F3B47D82");
        //        map.put("token", "4dd652dc092743b78e8cdd72496ba1861543923025867");
        if (loadType == MSG_LOAD_DATA) {
            mNetPresenter.getObject(mContext, NetConstants.URL.GET_FASHION_RECOMMEND, map, FashionRecommendBean.class, MSG_LOAD_DATA);
        } else if (loadType == MSG_REFRESH) {
            mNetPresenter.getObject(mContext, NetConstants.URL.GET_FASHION_RECOMMEND, map, FashionRecommendBean.class, MSG_REFRESH);
        } else if (loadType == MSG_LOAD_MORE) {
            mNetPresenter.getObject(mContext, NetConstants.URL.GET_FASHION_RECOMMEND, map, FashionRecommendBean.class, MSG_LOAD_MORE);
        }
    }

    @Override
    public void onLoadPre(int msgCode) {
        showLoadingView();
    }

    @Override
    public void onLoadSuccess(Object result, int msgCode) {
        hideLoadingView();
        hideEmptyView();
        setFashionData(result, msgCode);
    }

    /**
     * 设置时尚趋势数据
     */
    private void setFashionData(Object result, int msgCode) {
        FashionRecommendBean bean = (FashionRecommendBean) result;
        if (bean != null) {
            mPageCount = bean.getPageCount();
            mRecommendDataList = bean.getList();
            if (mRecommendDataList != null && mRecommendDataList.size() > 0) {
                if (msgCode == MSG_LOAD_DATA || msgCode == MSG_REFRESH) {
                    mBrandAdapter.setData(mRecommendDataList);
                    mBrandAdapter.notifyDataSetChanged();
                    refreshLayout.finishRefresh();
                } else if (msgCode == MSG_LOAD_MORE) {
                    mBrandAdapter.getData().addAll(mRecommendDataList);
                    mBrandAdapter.notifyDataSetChanged();
                    refreshLayout.finishLoadMore();
                }
            } else {
                if (msgCode == MSG_REFRESH) {
                    refreshLayout.finishRefresh();
                    showEmptyView(false);
                } else if (msgCode == MSG_LOAD_MORE) {
                    refreshLayout.finishLoadMore();
                    toast("没有更多的数据了~");
                }
            }
        }
    }

    @Override
    public void onLoadFail(int errorCode, String errorMsg, int msgCode) {
        hideLoadingView();
        if (msgCode == MSG_REFRESH) {
            refreshLayout.finishRefresh();
        } else if (msgCode == MSG_LOAD_MORE) {
            refreshLayout.finishLoadMore();
        }
        showEmptyView(true);
        toast(errorCode + errorMsg);
    }


    @Override
    protected void onRefreshData(RefreshLayout refreshLayout) {
        currentPage = 1;
        getPersonalReport(MSG_REFRESH);
    }

    @Override
    protected void onLoadMoreData(RefreshLayout refreshLayout) {
        if (currentPage < mPageCount) {
            currentPage++;
            getPersonalReport(MSG_LOAD_MORE);
        }
    }

    @Override
    public SuperAdapter getAdapter() {
        mBrandAdapter = new FashionTrendBrandAdapter(mContext, mRecommendDataList, R.layout.item_fashion_brand);
        mBrandAdapter.enableLoadAnimation(480, new ScaleInAnimation());
        return mBrandAdapter;
    }


    @Override
    public int getSpanCount() {
        return 3;
    }

    @Override
    public void onAdapterItemClick(View itemView, int viewType, int position) {
        if (mBrandAdapter != null && mBrandAdapter.getData() != null) {
            FashionRecommendBean.ListBean listBean = mBrandAdapter.getData().get(position);
            FashionBrandBean.setFashionBrandBean(listBean);

            mDressGuideFragment = (DressGuideFragment) getParentFragment();
            if (mDressGuideFragment != null) {
//                mDressGuideFragment.showThemeItemFragment();
//                mDressGuideFragment.getThemeItemFragment().refresh();
            }

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNetPresenter != null) {
            mNetPresenter.onDestroy();
        }
    }


    private void showEmptyView(boolean isError) {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.VISIBLE);
            mEmptyView.setBtnVisiable(true);
            if (isError) {
                mEmptyView.setErrorContent("数据加载失败，请重试~");
            } else {
                mEmptyView.setErrorContent("没有图片数据，请重试~");
            }
        }
    }

    private void hideEmptyView() {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.GONE);
        }
    }

    private void showLoadingView() {
        mLoadingView.setVisibility(View.VISIBLE);
    }

    private void hideLoadingView() {
        mLoadingView.setVisibility(View.GONE);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_fashion_trend;
    }

    @Override
    public void onEventMainThread(EventMessage event) {
        super.onEventMainThread(event);
        if (event.getCode() == EventCode.CODE_REFRESH_VIEW_NUM) {
            //刷新浏览数量
            int id = (int) event.getValue();
            updateCollectOrViewNum(0, id, 0);
        } else if (event.getCode() == EventCode.CODE_REFRESH_LIKE_NUM) {
            LikeEventInfo bean = (LikeEventInfo) event.getValue();
            if (bean != null) {
                int id = bean.getId();
                //0是取消收藏 1收藏
                int like = bean.getLike();
                updateCollectOrViewNum(1, id, like);
            }
        }
    }

    private void updateCollectOrViewNum(int index, int id, int like) {
        if (index == 0) {
            if (mBrandAdapter != null && mBrandAdapter.getData() != null) {
                for (int i = 0; i < mBrandAdapter.getData().size(); i++) {
                    if (id == mBrandAdapter.getData().get(i).getId()) {
                        int viewNum = mBrandAdapter.getData().get(i).getViewNum();
                        viewNum++;
                        mBrandAdapter.getData().get(i).setViewNum(viewNum);
                        mBrandAdapter.notifyItemChanged(i);
                    }
                }
            }
        } else {
            if (mBrandAdapter != null && mBrandAdapter.getData() != null) {
                for (int i = 0; i < mBrandAdapter.getData().size(); i++) {
                    if (id == mBrandAdapter.getData().get(i).getId()) {
                        int likeNum = mBrandAdapter.getData().get(i).getLikeNum();
                        if (like == 0) {
                            //收藏数-1
                            likeNum--;
                        } else {
                            //收藏数+1
                            likeNum++;
                        }
                        mBrandAdapter.getData().get(i).setLikeNum(likeNum);
                        mBrandAdapter.notifyItemChanged(i);
                    }
                }
            }
        }
    }
}
